import path from 'path';
import fs from 'fs';
import { Request, Response, NextFunction } from 'express';
import _ from 'lodash';
import { getShop, getIdShop, createShop, updateShop, deleteShop, shopStatusChange, createFile, updateFile, findFileById, deleteFileById, byKeyWordSelect } from './shop.service';
import { getFavorite } from '../favorites/favorites.service';
import { cornerDestroyById } from '../corner/common.service';

/**
 * 获取内容
 */
export const index = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  let status = request.query.status
  let type = request.query.type
  let pageNo = request.query.pageNo

  let user = request.user;
  let userId = 0
  if (user && user.id > 0) {
    userId = user.id;
  }

  const data = await getShop(parseInt(`${status}`, 10), -1, parseInt(`${type}`, 10), 10, parseInt(`${pageNo}`, 10), userId);
  for (const item of data.data as any) {
    if ("image_id" in item && item.image_id > 0) {
      const imgData = await findFileById(item.image_id, 0, 0, 'medium')
      item.cover = imgData[0];
    }
  }
  response.send(data);
}

/**
 * 获取内容(按 ID 查找)
 */
export const shopDetail = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const { postId } = request.params;

  // 调取内容
  try {
    const data = await getIdShop(parseInt(postId, 10));

    const user = request.user;
    
    if (user && user.id > 0) {
      let favoriteParam = { user_id: user.id, type: 13, target_id: data.id }
      let favorite = await getFavorite(favoriteParam);
      data.favorite = (favorite as any).length > 0 ? favorite[0] : null;
    }

    // 做出响应
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 创建内容
 */
export const store = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  let shopModel = request.body;
  shopModel.status = 1;
  
  /* 创建 */
  if (shopModel.id && shopModel.id > 0) {
    let image_id = shopModel.image_id
    let img = await findFileById(image_id, 0, 0);
    if (!img || img.length === 0) {
      let imgs = await findFileById(0, shopModel.id, 13);
      if (imgs && imgs.length > 0) {
        shopModel.image_id = imgs[imgs.length - 1].id
      }
    }
    const data = await updateShop(shopModel, parseInt(shopModel.id, 10));
    response.send(data);
  } else {
    const data = await createShop(shopModel);
    response.send(data);
  }
}

/**
 * 按关键词搜索
 */
export const selectByKey = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取关键词
  const { keyWord } = request.query;

  try {
    const data = await byKeyWordSelect(keyWord);
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 更新内容
 */
export const update = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取更新内容 ID
  const { postId } = request.params;

  // 获取内容
  const post = _.pick(request.body, [
    'status',
    'name_zh',
    'name_ug',
    'address_zh',
    'address_ug',
    'longitude',
    'latitude',
    'detailed_zh',
    'detailed_ug',
    'contactPerson_zh',
    'contactPerson_ug',
    'phoneNum'
  ]);

  // 更新
  try {
    const data = await updateShop(post, parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 删除内容
 */
export const destroy = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取删除内容 ID
  let { postId } = request.body;
  if (!postId) {
    postId = request.params
  }

  if(!postId) {
    response.send("你的参数呢？");
    return;
  }
  
  if (postId instanceof Object) {
    postId = postId.postId;
  }
  
  // 删除
  try {
    const data = await deleteShop(parseInt(postId, 10));
    if (data) await cornerDestroyById(parseInt(postId, 10), 13);
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 状态
 */
export const status = async (
  request: Request,
  response: Response,
  next: NextFunction,
) => {
  // 获取内容 ID
  const postId = request.body.id;


  // 获取内容
  const post = _.pick(request.body, ['status']);

  // 执行
  try {
    const data = await shopStatusChange(parseInt(postId, 10), post);
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 上传文件
 */
export const uploads = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取类型
  let { target_type, target_id } = request.body;
  if (target_id === undefined) {
    target_type = request.query.target_type;
    target_id = request.query.target_id;
  }

  // 文件信息
  const fileInfo = _.pick(request.file, [
    'id',
    'target_id',
    'target_type',
    'url',
    'originalname',
    'mimetype',
    'filename',
    'size'
  ])

  fileInfo['url'] = "/shop/";
  fileInfo['target_type'] = parseInt(`${target_type}`, 10);
  fileInfo['target_id'] = parseInt(`${target_id}`, 10);

  try {
    // 保存文件信息
    const data = await createFile({
      ...fileInfo,
      ...request.fileMataData,
      //target_type: parseInt(`${target_type}`, 10), // target_type: `${target_type}` // target_type: target_type as string  转换字符串两种写法
    })
    let post = {
      id: parseInt(`${target_id}`, 10),
      image_id: (data as any).insertId,
    }

    const shopData = await updateShop(post as any, parseInt(`${target_id}`, 10));

    // 做出响应
    response.status(200).send(shopData)
  } catch (error) {
    next(error);
  }
}

/**
 * 文件服务
 */
export const serve = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 从地址参数里得到文件 ID
  const { fileId } = request.params;

  try {
    // 查找文件信息
    const file = await findFileById(parseInt(fileId, 10), 0, 0);

    // 要提供的图像尺寸
    const { size } = request.query;

    // 文件名与目录
    let filename = file[0].filename;
    let root = 'uploads/shop/resized';
    let resized = 'resized';

    if (size) {
      // 可用的图像尺寸
      const imageSize = ['lerge', 'medium', 'thumbnail'];

      // 检查文件尺寸是否可用
      if (!imageSize.some(item => item == size)) {
        throw new Error('FILE_NOT_FOUND');
      }

      // 检查文件是否存在
      const fileExist = fs.existsSync(
        path.join(root, resized, `${filename}-${size}`),
      )

      // 设备文件名与目录
      if (fileExist) {
        filename = `${filename}-${size}`;
        root = path.join(root, resized);
      }
    }
    
    // 做出响应
    response.sendFile(filename, {
      root,
      headers: {
        'Content-Type': file[0].mimetype
      }
    });
  } catch (error) {
    next(error);
  }
}

/**
 * 获取文件名
 */
export const getFileName = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取文件 ID
  const { fileId } = request.body;
  let file = await findFileById(fileId, 0, 0)
  if (!file || file.length <= 0) {
    response.send({
      status: 2,
      msg: 'not found'
    })
    return;
  }
  let result = await deleteFileById(file[0])

  response.send({
    status: 1,
    msg: 'ok'
  })

}
